"use strict"
const mvc = require("cosjs.mvc");
const handle = mvc.library("handle","成员管理","admin/members")

exports.index = function(){
    let level = this.session.get("level");
    let data = {"level":level, "brows":{}};
    if(level < 10){
        return handle.index.call(this,data);
    }
    let branchModel = this.model.admin("branch");
    return branchModel.get(null,["name"]).then(ret=>{
        for(let k in ret){
            data['brows'][k] = ret[k]['name']
        }
        return handle.index.call(this,data);
    })
}
//游戏服务器列表管理
exports.page = function (){
    let query = {};
    let level = this.session.get("level");
    if(level < 10){
        query["branch"] = {"$in":this.branch};
    }
    return handle.page.call(this,query);
};

exports.save = function () {
    this.output = "json";
    let act = this.get('act');
    let level = this.session.get("level")||0;
        let saveLevel = this.get("level",'int');
        
    if(saveLevel >= level){
        return this.error(`你不能添加/编辑权限大于等于${level}的用户`)
    }

    if(level < 10) {
        if(act == 'del'){
            return del_member_branch.call(this);
        }
    }

    return handle.save.call(this,save_member_filter)

}

function save_member_filter(t,d){
    if(t=='add'){
        return save_member_add.call(this,d)
    }
    else if(t=="edit"){
        return save_member_edit.call(this,d)
    }
}

function del_member_branch() {
    let id = this.get('id','string');
    if ( !id ) {
        return this.error('args[id] empty');
    }

    let keys = ["branch","level"];
    let  membersModel = this.model.admin('members');
    return membersModel.get(id,keys).then(ret=>{
        if(!ret){
            return this.error('用户不存在')
        }
        let level = this.session.get("level");
        if( level < ret['level'] ){
            return this.error('不能删除权限比自己高的成员')
        }
        let branch = ret["branch"]||[]
        let i = branch.indexOf(this.branch)
        if(i<0){
            return this.error('不存在此用户')
        }
        branch.splice(i,1)
        return membersModel.set(id,"branch",branch);
    })
}

function save_member_add(info) {
    let xcode = info['xcode']|| (Date.now()).toString('32')
    info['xcode'] = mvc.model.admin('members/password',xcode);

    let level = this.session.get("level")||0;
    if(level < 10){
        info['branch'] = [this.branch];
    }
}

function save_member_edit(info){
    if(!info['xcode']){
        delete info['xcode'];
    }
    else{
        info['xcode'] = mvc.model.admin('members/password',info['xcode']);
    }

    let id = this.get('id','string');
    let level = this.session.get("level")||0;
    //编辑自己账号
    if(id === this.session.uid ){
        delete info['level'];
        delete info['branch'];
        delete info['status'];
    }
    if( level < 10 ){
        delete info['branch'];
    }

}






